import { defineStore } from 'pinia'
import { getComments, postComment, likeComment, updateUserInfo } from '@/api/comment'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

export const useCommentStore = defineStore('comment', {
  state: () => ({
    comments: [],
    currentCategory: 'all',
    sortType: 'newest',
    searchKeyword: '',
    categories: [
      { id: 'all', name: '全部' },
      { id: 'study', name: '学习' },
      { id: 'life', name: '生活' },
      { id: 'other', name: '其他' }
    ],
    loading: false,
  }),

  getters: {
    filteredComments: (state) => {
      let result = [...state.comments]
      
      // 分类筛选
      if (state.currentCategory !== 'all') {
        result = result.filter(comment => comment.category === state.currentCategory)
      }
      
      // 关键词搜索
      if (state.searchKeyword) {
        const keyword = state.searchKeyword.toLowerCase()
        result = result.filter(comment => 
          comment.content.toLowerCase().includes(keyword) ||
          (comment.tags && comment.tags.some(tag => tag.toLowerCase().includes(keyword)))
        )
      }
      
      // 排序
      switch (state.sortType) {
        case 'newest':
          result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          break
        case 'hottest':
          result.sort((a, b) => (b.replyCount || 0) - (a.replyCount || 0))
          break
        case 'mostLiked':
          result.sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0))
          break
      }
      
      return result
    }
  },

  actions: {
    async fetchComments() {
      this.loading = true
      try {
        const res = await getComments({
          category: this.currentCategory !== 'all' ? this.currentCategory : undefined,
          sortType: this.sortType,
          keyword: this.searchKeyword || undefined
        })
        
        if (res.code === 200 && res.data) {
          this.comments = res.data.list || res.data || []
        }
      } catch (error) {
        console.error('获取评论失败:', error)
        ElMessage.error('获取评论失败')
        this.comments = []
      } finally {
        this.loading = false
      }
    },

    async postComment(commentData) {
      try {
        const userStore = useUserStore()
        const userId = userStore.getUserProfile.id
        
        const res = await postComment({
          ...commentData,
          userId
        })
        
        if (res.code === 200 && res.data) {
          this.comments.unshift(res.data)
          ElMessage.success('发布成功')
          return true
        } else {
          ElMessage.error('发布失败')
          return false
        }
      } catch (error) {
        console.error('发布评论失败:', error)
        ElMessage.error('发布失败')
        return false
      }
    },

    async likeComment(commentId) {
      try {
        const res = await likeComment(commentId)
        
        if (res.code === 200) {
          const comment = this.comments.find(c => c.id === commentId)
          if (comment) {
            comment.likeCount = (comment.likeCount || 0) + 1
          }
          ElMessage.success('点赞成功')
        } else {
          ElMessage.error('点赞失败')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        ElMessage.error('点赞失败')
      }
    },

    changeCategory(category) {
      this.currentCategory = category
      this.fetchComments()
    },

    changeSortType(sortType) {
      this.sortType = sortType
      this.fetchComments()
    },

    setSearchKeyword(keyword) {
      this.searchKeyword = keyword
      this.fetchComments()
    }
  }
}) 